from django.shortcuts import render
from django.http import HttpResponse, JsonResponse
from django.views.decorators.csrf import csrf_exempt
from .models import News, NewsTag, NewsComment
from django.http import Http404
from utils import restful
from .serializers import NewsTagSerializer, NewsSerializer
from django.views.decorators.http import require_GET, require_POST
from django.conf import settings
from .serializers import NewsCommentSerializer
# 针对 form的请求 redirect(reverse)
from django.contrib.auth.decorators import login_required
from django.shortcuts import redirect, reverse
from utils.decorators import dj_login_required
# 首页
def index(request):
    tags = NewsTag.objects.all()
    # select_related 一般都用是用在外键 优化查询sql语句 select * form ,  内连接 left join
    # orm会把sql对象转成python 加上 defer 忽略掉
    newses = News.objects.defer('content').select_related('author', 'tag').all()[0:settings.ONE_PAGE_NEWS_COUNT]
    context = {
        "tags": tags,
        "newses": newses,
    }
    # from django.utils.timezone import now
    # from datetime import datetime
    # # 国际时间 带时区 就可以跨时区
    # print(now())
    # # 下面这个是不是当前的时候
    # print(datetime.now())
    return render(request, 'news/index.html', context=context)


def news_detail(request, news_id):
    try:
        # get 获取数据 会报错
        # News.objects.filter(id=news_id).first() 如果存在  返回None
        # get 不存在 抛出异常
        news = News.objects.select_related('author', 'tag').get(id=news_id)
        return render(request, 'news/news_detail.html', context={"news": news})
    except News.DoesNotExist:
        # 404 Page 404 Not Found 页面未找到
        raise Http404
        # return render(request, '404.html')


@require_POST
@dj_login_required  # dj_login_required(add_news_comment)
def add_news_comment(request):
    news_id = request.POST.get("news_id")
    content = request.POST.get("content")
    news = News.objects.filter(id=news_id).first()
    if news:
        if content:
            # 创建一条新的评论
            # new_comment =NewsComment(content=content, news=news,author=request.user)
            # news_comment.save()
            comment = NewsComment.objects.create(content=content, news=news, author=request.user)
            serializer = NewsCommentSerializer(comment)
            # data=  {"comment": {"comment": "xxx"}}
            return restful.result(data={"comment": serializer.data})
            # data = {"content":"xx", }
            # return restful.result(data=serializer.data)
        return restful.params_error(message="评论不能为空")
    return restful.params_error(message="新闻不存在")


@require_GET
def comment_with_news(request):
    news_id = int(request.GET.get("news_id"))
    if news_id:
        news = News.objects.filter(id=news_id).first()
        # 获取当前新闻下所有评论
        comments = news.comment.all()
        serializer = NewsCommentSerializer(comments, many=True)
        return restful.result(data={"comments": serializer.data})



@require_GET
def news_list(request):
    page = int(request.GET.get('page', 1))  # str  - 1
    tag_id = int(request.GET.get('tag_id', 0))
    # limit  从第几条数据开始 要取几条 # 一页只有1条
    # 0-1  1-2
    # 开始位置 结束位置 0 + (0+1) page+1 page=2  1 - (1+1=2 ) 2 - 3
    page_start = settings.ONE_PAGE_NEWS_COUNT * (page - 1)
    page_end = page_start + settings.ONE_PAGE_NEWS_COUNT
    # newses querySet
    if tag_id:
        newses = News.objects.filter(tag=tag_id).all()[page_start:page_end]
    else:
        newses = News.objects.all()[page_start:page_end]
    # print(newses) # <QuerySet [<News: News object (3)>, <News: News object (2)>, <News: News object (1)>]>
    # print(newses.values()) # <QuerySet [{id:"1",}, {"id": 2}]>
    # print(type(newses.values())) # <class 'django.db.models.query.QuerySet'>
    # entry_list = list(newses.values())
    # print(entry_list) #  [{id:"1",}, {"id": 2}]
    # print(type(entry_list)) # <class 'list'>
    # for news in entry_list:
    #     # print(news) # {} , {}
    #     tag_id = news["tag_id"]
    #     author_id= news["author_id"]
    #     tag= NewsTag.objects.filter(id=tag_id).first()
    #     tag_name = tag.name
    #     news["tag_name"] = tag_name
    # 要同时序列化多条
    serializer = NewsSerializer(newses, many=True)
    return restful.result(data={"newses": serializer.data})


# 搜索页
def search(request):
    # tag = NewsTag.objects.first()
    # for i in range(30):
    #     title = '新闻{}'.format(i+1)
    #     content = '新闻内容{}'.format(i+1)
    #     desc = '新闻描述{}'.format(i+1)
    #     thumbnail_url = 'http://onj3s3zfw.bkt.clouddn.com/o_1cmq2acf9180h1rep142h1coa138d7.jpg'
    #     News.objects.create(title=title, content=content, desc=desc, thumbnail_url=thumbnail_url, tag=tag, author=request.user)
    return render(request, 'news/search.html')


# @csrf_exempt  # django.views.decorators.csrf
def test_data(request):
    # {}
    # return HttpResponse('{"user": "which"}')
    json = {"data": [{"id": 1, "username": "which"}, {"id": 2, "username": "qq"}]}
    return JsonResponse(json)


def test_form(request):
    return render(request, 'news/test_form.html')
